//
//  STDSAttrbParticle.cpp
//  STDSRenderSDKIOS
//
//  Created by 陈学明 on 2023/7/10.
//

#include "STDSAttrbParticle.hpp"

STDSAttrbParticle::STDSAttrbParticle() {
    mCountParticle = 1;
    mCountVertices = 1;
    _reset();
}

void STDSAttrbParticle::setParticleStore(shared_ptr<STDSParticleKit> particleStore) {
    mParticleStore = particleStore;
    SAFE_DELETE_ARRAY(mArrVex);
    mCountVertices = (int)particleStore->getVertexCount();
    mCountParticle = (int)particleStore->getVertexCount();
    
    auto vexs = particleStore->getVertex();
    mArrVex = new float[mCountVertices * particleStore->getUnitLength()];
    memcpy(mArrVex, vexs.data(), vexs.size()*sizeof(STDSParticleUnit));
}

void STDSAttrbParticle::draw() {
    if (mCountVertices <= 0)
        return;

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glVertexAttribPointer((GLuint) mPosVex, 3, GL_FLOAT, GL_FALSE, 0, mArrVex);
    glEnableVertexAttribArray((GLuint) mPosVex);

    if(mPosTex >= 0){
        glVertexAttribPointer((GLuint) mPosTex, 2, GL_FLOAT, GL_FALSE, 0, mArrTex);
        glEnableVertexAttribArray((GLuint) mPosTex);
    }

    if(mPosClr >= 0){
        glVertexAttribPointer((GLuint) mPosClr, 4, GL_FLOAT, GL_FALSE, 0, mArrClr);
        glEnableVertexAttribArray((GLuint) mPosClr);
    }

    mDrawFunc(mArrIdx, mCountVertices, 0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void STDSAttrbParticle::_resetDrawFunc(){
    mDrawFunc = STDSGLFunctions::draw_ARR_POINTS;
}

void STDSAttrbParticle::_resetCount() {
    mCountVertices = mCountParticle;
}

void STDSAttrbParticle::_resetIdx(){
    SAFE_DELETE_ARRAY(mArrIdx);
    if (mUseIdx) {
        mArrIdx = new uint16_t[mCountVertices];
        for (int i = 0; i < mCountVertices; ++i) {
            mArrIdx[i] = (uint16_t) i;
        }
    }
}

void STDSAttrbParticle::_resetVex() {
    SAFE_DELETE_ARRAY(mArrVex);
    int size = mCountVertices * mParticleStore->getUnitLength();
    mArrVex = new float[size];
    for (int i = 0; i < size; ++i) {
        mArrVex[i] = 0.f;        
    }
}
